<?php

namespace App\Services;


use App\Models\MasterAccess;
use App\Models\MasterMenu;
use App\Models\MasterPermission;
use common\enum\CommonEnum;
use Illuminate\Support\Facades\Auth;

class MenuService
{
    public static function menuList($roleId)
    {
        $query = MasterMenu::select();
        if ($roleId != CommonEnum::ADMIN_ROLE_ID) {
            //获得该角色所有菜单
            $menuIds = MasterPermission::selectRaw('DISTINCT `menu_id` AS menu_id')
                ->where([
                    'role_id' => $roleId
                ])
                ->pluck('menu_id')
                ->toArray();
            $query->whereIn('id', $menuIds);
        }
        $menus = $query->get()->toArray();
        $menusIds = array_column($menus, 'id');
        $menus = array_combine($menusIds, $menus);
        foreach ($menus as $k => $m) {
            $parent = $m['parent'];
            if (!empty($parent) && !empty($menus[$parent])) {
                $menus[$parent]['children'][] = $m;
                unset($menus[$k]);
            }
        }
        $menus = array_values($menus);
        return $menus;
    }
}